<template>
  <!--<div ref="barchart" class="bar-chart" id="org-chart"></div>-->
  <div :style="{height: chartHeight + 'px'}" @click="closeTips">
    <div ref="barchart" style="height: 100%;"></div>
  </div>
</template>

<script>
import { queryOrgDetailView } from "@/api/modules/org";

import { title } from "@/settings";
export default {
  props: {
    chartData: {
      type: Object,
      default: () => {},
    },
    stype: {
      type: String,
      default: "",
    },
  },
  watch: {
    chartData() {
      this.initChart();
    },
  },
  data() {
    return {
      chart: null,
      orgInfoForm: {},
      timer: null,
      showTip: false,
      index: 0,
      chartHeight: 1000,
      showTable:false
    };
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  mounted() {
    // this.initChart();
  },
  methods: {
    closeTips(){
      let that = this;
      this.chart.dispatchAction({
        type: "hideTip",
      });
    },
    formatterHover(parms, ticket, callback) {
      this.index++;
      // if (!this.showTip) {
      //   this.showTip = true;
      //   console.log("33333", parms);
      //   queryOrgDetailView({ orgId: parms.data.id }).then((response) => {
      //     if (response.code == 200) {
      //       this.orgInfoForm = response.data;
      //       const txt = `
      //         <b>${parms.name}</b> <br/>
      //         请求得到的数据: ${response.code}
      //         `
      //       callback(ticket, txt);
      //     }
      //   });
      //   return `
      //     <b>${parms.name}</b> <br/>
      //     请求得到的数据: loading
      //     `;
      // }
      let hiddenOrgSetting = ""
      if (parms.data.children.length === 0) {
        hiddenOrgSetting = "style='display: none'"
      }
      queryOrgDetailView({ orgId: parms.data.id }).then((response) => {
        if (response.code == 200) {
          this.orgInfoForm = response.data;
          const txt =
            "<table\n" +
            '          class="sub-top-table"\n' +
            '          style="width:500px;height:600px;"\n' +
            '          v-if="showTable"\n' +
            "        >\n" +
            "<tr>\n" +
            '<th colspan="12">' + this.orgInfoForm.orgName + '</th>\n' +
            "</tr>\n" +
            "          <tr>\n" +
            '            <th rowspan="4" colspan="2">人编情况</th>\n' +
            "            <th colspan=\"2\"></th>\n" +
            '            <th colspan="2">行政</th>\n' +
            '            <th colspan="2">单列</th>\n' +
            '            <th colspan="2">工勤</th>\n' +
            '            <th colspan="2">事业</th>\n' +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">编制数量</th>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationAdmin.plan +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationSingle.plan +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationWork.plan +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationCause.plan +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">实有人员</th>\n" +
            '             <td colspan="2">' +
            this.orgInfoForm.organizationAdmin.existing +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationSingle.existing +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationWork.existing +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationCause.existing +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">超空</th>\n" +
            '             <td colspan="2">' +
            this.orgInfoForm.organizationAdmin.state +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationSingle.state +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationWork.state +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.organizationCause.state +
            "</td>\n" +
            "          </tr>\n" +
            "\n" +
            // "          <tr " + hiddenOrgSetting + ">\n" +
            "          <tr>\n" +
            '            <th rowspan="5" colspan="2">机构设置</th>\n' +
            "            <th colspan=\"2\"></th>\n" +
            "            <th>副局</th>\n" +
            "            <th>正处</th>\n" +
            '            <th colspan="2">副处</th>\n' +
            "            <th>正科</th>\n" +
            "            <th>副科</th>\n" +
            '            <th colspan="2">股级</th>\n' +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">内设机构</th>\n" +
            "            <td>" +
            this.orgInfoForm.bureauDeputy.internal +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.division.internal +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.divisionDeputy.internal +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.department.internal +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentDeputy.internal +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.group.internal +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">下设机构</th>\n" +
            "            <td>" +
            this.orgInfoForm.bureauDeputy.under +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.division.under +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.divisionDeputy.under +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.department.under +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentDeputy.under +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.group.under +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">派出机构</th>\n" +
            "            <td>" +
            this.orgInfoForm.bureauDeputy.dispatch +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.division.dispatch +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.divisionDeputy.dispatch +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.department.dispatch +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentDeputy.dispatch +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.group.dispatch +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">事业机构</th>\n" +
            "            <td>" +
            this.orgInfoForm.bureauDeputy.cause +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.division.cause +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.divisionDeputy.cause +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.department.cause +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentDeputy.cause +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.group.cause +
            "</td>\n" +
            "          <tr>\n" +
            '            <th rowspan="4" colspan="2">职数及配备</th>\n' +
            "            <th colspan=\"2\"></th>\n" +
            "            <th>部门<br/>领导<br/>正职</th>\n" +
            "            <th>部门<br/>领导<br/>副职</th>\n" +
            '            <th colspan="2">与部门领导<br/>同级别的其<br/>他领导</th>\n' +
            "            <th>内设<br/>机构<br/>领导<br/>正职</th>\n" +
            "            <th>内设<br/>机构<br/>领导<br/>副职</th>\n" +
            '            <th colspan="2">与内设机构<br/>领导同级别<br/>的其他领导</th>\n' +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">应配</th>\n" +
            "            <td>" +
            this.orgInfoForm.departmentLead.plan +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentLeadDeputy.plan +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.sameDepartmentLead.plan +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.internalLead.plan +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.internalLeadDeputy.plan +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.sameInternalLead.plan +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">实配</th>\n" +
            "            <td>" +
            this.orgInfoForm.departmentLead.existing +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentLeadDeputy.existing +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.sameDepartmentLead.existing +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.internalLead.existing +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.internalLeadDeputy.existing +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.sameInternalLead.existing +
            "</td>\n" +
            "          </tr>\n" +
            "          <tr>\n" +
            "            <th colspan=\"2\">超空</th>\n" +
            "            <td>" +
            this.orgInfoForm.departmentLead.state +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.departmentLeadDeputy.state +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.sameDepartmentLead.state +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.internalLead.state +
            "</td>\n" +
            "            <td>" +
            this.orgInfoForm.internalLeadDeputy.state +
            "</td>\n" +
            '            <td colspan="2">' +
            this.orgInfoForm.sameInternalLead.state +
            "</td>\n" +
            "          </tr>\n" +
            "        </table>";
          setTimeout(function () {
            callback(ticket, txt);
            document.querySelector(".sub-top-table").parentNode.style =
              "top: 100px;left: 255px;position:fixed;display: block; border-style: solid;white-space: nowrap;z-index: 9999999;will-change: transform;box-shadow: rgb(0 0 0 / 20%) 1px 2px 10px;background-color: rgb(255, 255, 255);border-width: 1px;border-radius: 4px;color: rgb(102, 102, 102);font: 14px / 21px 'Microsoft YaHei';padding: 10px;border-color: lightsteelblue;pointer-events: none;";
          }, 100);
          if (this.index === 2) {
            setTimeout(function () {
              document.querySelector(".sub-top-table").parentNode.style =
                "top: 100px;left: 255px;position:fixed;display: block; border-style: solid;white-space: nowrap;z-index: 9999999;will-change: transform;box-shadow: rgb(0 0 0 / 20%) 1px 2px 10px;background-color: rgb(255, 255, 255);border-width: 1px;border-radius: 4px;color: rgb(102, 102, 102);font: 14px / 21px 'Microsoft YaHei';padding: 10px;border-color: lightsteelblue;pointer-events: none;";
            }, 120);
          }
        }
      });
      // let temp =
      //   "济南市公安局,指挥部,警务保障部,人口管理支队,出入境管理局,历下区分局,历城区分局,槐荫区分局,天桥区分局,长清区分局," +
      //   "xxx处4,xxx处6,xxx处7,";
      // if (temp.indexOf(parms.data.name) !== -1) {

      // } else {
      //   return "";
      // }

      return `
        <b>${parms.name}</b> <br/>
        请求得到的数据: loading
        `;
    },

    // 节点点击事件
    treeNodeclick(param) {
      /* true 代表点击的是圆点
       fasle 表示点击的是当前节点的文本
    */
      // if (param.event.target.culling === true) {
      //   console.log("param", param);
      //   return;
      // } else if (param.event.target.culling === false) {
      //   let args = param.data; //当前节点及其子节点的值
      //   let level = param.data.level; //当前节点的层级 eg:"1-1-0",可以通过level判断当前的层级，从而进行不同的操作
      //   console.log("args", args);
      //   console.log("level", level);
      // }

      // if (param.dataType == "node") {
      //   console.log("点击了节点", param);
      // } else {
      //   console.log("点击了边", param);
      // }

      if (param.event.target.culling === true) {
        alert("点击了节点");
      } else if (param.event.target.culling === false) {
        if (
          param.data.children.length !== 0 &&
          param.treeAncestors.length - 1 !== 1
        ) {
          console.log("pa", param);
          this.$emit("updateFlag", param.data);
        }
      }
    },
    initChart() {
      // console.log("charData", this.chartData);
      this.chart = this.$echarts.init(this.$refs.barchart);
      let option = this.getOption();
      let that = this;
      let timer;
      this.chart.on("mouseover", "series", function (params) {
        // console.log(params);
        timer = setTimeout(() => {
          //这里可以发送请求
          that.chart.dispatchAction({
            type: "showTip",
            seriesIndex: 0,
            dataIndex: params.dataIndex,
            // position: function (point, params, dom, rect, size) {
            //   //  size为当前窗口大小
            //   if (size.viewSize[0] / 2 >= rect.x) {
            //     //其中point为当前鼠标的位置
            //     return [rect.x + 50, "10%"];
            //   } else {
            //     //其中point为当前鼠标的位置
            //     return [rect.x - 700, "10%"];
            //   }
            // },
            position: ["10px", "100px"],
          });
        }, 200); //鼠标悬停 0.5 秒才触发事件
      });
      this.chart.on("mouseout", "series", function (params) {
        // that.chart.dispatchAction({
        //   type: "hideTip",
        // });

        clearTimeout(timer);

      });

      this.chart.setOption(option);
      //点击事件
      // var temp = this.chart;

      // var container = document.getElementById("treeChart");
      // var container2 = document.getElementById("org-chart");

      // this.chart.on("click", function (params) {
      //   that.chart.dispatchAction({
      //     type: "hideTip",
      //   });
      //   clearTimeout(timer);
      //   if (params.componentType === "series") {
      //     // 点击到了 series 上
      //     if (!params.value) {
      //       // 点击的节点有子分支（可点开）
      //       console.log("22222222222");
      //       var allNode = 0;
      //       var nodes = temp._chartsViews[0]._data._graphicEls;
      //       const dep = temp._chartsViews[0]._data.tree.root.height; // 获取树高
      //       console.log(temp._chartsViews[0]._data, "层级");
      //       for (var i = 0, count = nodes.length; i < count; i++) {
      //         var node = nodes[i];
      //         if (node === undefined) continue;
      //         allNode++;
      //       }

      //       const height = 1200;
      //       const width = window.innerWidth;
      //       const currentHeight = 35 * allNode;
      //       const currentWidth = 240 * dep;
      //       const newHeight = Math.max(currentHeight, height);
      //       const newWidth = Math.max(currentWidth, width);

      //       container.style.height = newHeight + "px";
      //       // container2.style.width = newWidth + 'px';

      //       temp.resize();
      //     }
      //   }
      // });

      // var allNode = 0;
      // var nodes = this.chart._chartsViews[0]._data._graphicEls;
      // const dep = this.chart._chartsViews[0]._data.tree.root.height; // 获取树高
      // console.log(this.chart._chartsViews[0]._data, "层级");
      // for (var i = 0, count = nodes.length; i < count; i++) {
      //   var node = nodes[i];
      //   if (node === undefined) continue;
      //   allNode++;
      // }

      // const height = 1200;
      // const width = window.innerWidth;
      // const currentHeight = 35 * allNode;
      // const currentWidth = 240 * dep;
      // const newHeight = Math.max(currentHeight, height);
      // const newWidth = Math.max(currentWidth, width);

      // container.style.height = newHeight + "px";
      // container2.style.width = newWidth + "px";
      this.chart.resize();
      // container.scrollTo(0,300)
      this.$nextTick(() => {
        option && this.chart.setOption(option)
        const eleArr = Array.from(new Set(this.chart._chartsViews[0]._data._graphicEls))
        // const treeDepLength = myChart._chartsViews[0]._data.tree.root.height                            // 获取树的高度
        // const itemHeight = 100       // 设置每层树的间距（垂直型树高）
        // let currentHeight = itemHeight * (treeDepLength + 1) || itemHeight
        const itemHeight = 30
        const currentHeight = itemHeight * (eleArr.length - 1) || itemHeight
        const newHeight = Math.max(currentHeight, itemHeight)
        this.chartHeight = newHeight
        this.chart.resize({
          height: newHeight
        })
      })
    },
    getOption() {
      let option = {
        tooltip: {
          trigger: "item",
          triggerOn: "none",
          formatter: this.formatterHover,
          // extraCssText: "width:500px;height:600px;",
          position: function (point, params, dom, rect, size) {
            //  size为当前窗口大小
            if (size.viewSize[0] / 2 >= point[0]) {
              //其中point为当前鼠标的位置
              return [point[0] + 50, "10%"];
            } else {
              //其中point为当前鼠标的位置
              return [point[0] - 700, "10%"];
            }
          },
        },

        legend: {
          // 设置图例组件需要在【series】中设置对应的【name】属性
          top: "7%",
          left: "1%",
          itemWidth: 25, // 设置宽度
          itemHeight: 15, // 设置高度
          itemGap: 20, // 设置间距
          // data: ["行政", "单列", "工勤", "事业"],
          data: [
            {
              // name: "内设",
              icon: "rectangle",
              itemStyle:{
                color:'#409EFF'
              }

            },
            {
              // name: "下设",
              icon: "rectangle",
              itemStyle:{
                color:'#5CBB7A'
              }
            },
            {
              // name: "派出",
              icon: "rectangle",
              itemStyle:{
                color:'#E6A23C'
              }
            },
            {
              // name: "事业",
              icon: "rectangle",
              itemStyle:{
                color:'#F56C6C'
              }
            }
          ],
        },

        series: [
          {
            type: "tree",
            id: 0,
            name: "内设",
            data: [this.chartData],
            top: "5%",
            left: "5%",
            bottom: "2%",
            right: "30%",
            symbolSize: 7,
            // edgeShape: "polyline",
            edgeForkPosition: "63%",
            initialTreeDepth: 2,

            roam:"move",
            // initialTreeDepth: -1,
            lineStyle: {
              width: 2,
            },
            label: {
              position: [10, 5],
              verticalAlign: "middle",
              align: "left",
              backgroundColor: "#fff",
              fontSize: 12,
              // formatter(v) {
              //   let text = v.name;
              //   if (text.length <= 20) {
              //     return `${text}`;
              //   } else {
              //     return (text = `${text.slice(0, 12)}...`);
              //   }
              // },
            },
            leaves: {
              label: {
                normal: {
                  verticalAlign: "middle",
                  align: "left",
                  backgroundColor: "#fff",
                  fontSize: 12,
                  fontWeight: "normal",
                },
              },
            },
            emphasis: {
              focus: "descendant",
            },
            //支持展开收缩
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750,
          },
          {
            type: "tree",
            id: 10,
            name: "下设",

          },
          {
            type: "tree",
            id: 11,
            name: "派出",
          },
          {
            type: "tree",
            id: 12,
            name: "事业",
          },
        ],
      };
      return option;l
    },
  },
};
</script>

<style lang="scss" scoped>
.bar-chart {
  width: 100%;
  height: 100%;
  background-color: #fff;
  &::v-deep .sub-top-table1 th {
    width: 78px;
  }
}
</style>
